const router = require('koa-router')()

const MySocket = require('../MySocket')
const Breath = require('../Breath')
let mySocket = null
let breath;
const getTurning = require('../utils')
router.get('/open', async (ctx, next) => {
    try {
        if (mySocket == null) {
            mySocket = new MySocket()
        }
        const {isOpened} = await mySocket.openBreath();
        if (!isOpened) {
            ctx.body = {
                code: 0,
                msg: '失败',
            }
        } else {
            if (breath == null) {
                breath = new Breath()
            }
            ctx.body = {
                code: 1,
                msg: '成功',
                time: new Date().getTime()
            }
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            msg: '失败',
        }
    }
})

router.get('/close', async (ctx, next) => {
    try {
        if (mySocket !== null) {
            await mySocket.closeBreath();
            mySocket = null
        }
        ctx.body = {
            code: 1,
            msg: '成功',
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            msg: '失败',
        }
    }
})

router.get('/record/start', async (ctx, next) => {
    const date = new Date()
    if (mySocket == null) {
        ctx.body = {
            code: 0,
            msg: 'mySocket实例不存在',
            time: date.getTime()
        }
        return;
    }
    breath.startRecord();
    ctx.body = {
        code: 1,
        msg: '成功',
        time: date.getTime()
    }
})

// /amplitude/ 0-15
router.get('/amplitude/:val', async (ctx, next) => {
    let amplitude = Number.parseInt(ctx.params.val);
    try {
        breath.setAmplify(amplitude);
        // await mySocket.setBreathAmplitude(amplitude);
        ctx.body = {
            code: 1,
            msg: '成功',
        }
    } catch (e) {
        ctx.body = {
            code: 0,
            msg: '失败',
        }
    }
})

router.get('/record/end', async (ctx, next) => {
    if (mySocket == null) {
        ctx.body = {
            code: 0,
            msg: 'mySocket实例不存在',
        }
        return;
    }
    if (breath == null) {
        ctx.body = {
            code: 0,
            msg: 'breath实例不存在',
        }
        return;
    }
    try {
        const ans = await breath.stopRecord();
        const {peakArr, troughArr} = getTurning(ans);
        console.log('数组第一时间：' + ans[0].timestamp, '最后一个时间，' + ans[ans.length - 1].timestamp);
        const date = new Date()
        ctx.body = {
            code: 1,
            msg: '成功',
            data: {
                records: ans,
                peakArr: peakArr,
                troughArr: troughArr
            },
            time: date.getTime()
        }
    } catch (e) {
        console.log(e);
        ctx.body = {
            code: 0,
            msg: '失败',
        }
    }
})

process.on('SIGINT', () => {
    mySocket.destroyBreath()
})

module.exports = router
